<?php
namespace app\index\controller;

use think\Exception;
use app\common\controller\Param;
use app\common\model\coin\CoinList;
use app\common\controller\Marcketline;
use app\common\model\trade\TradeLeveraged as Leveraged;
use app\common\model\coin\CoinUser;
use think\Db;
use app\common\model\user\Users;
use app\common\model\user\UserActParam;
use app\common\controller\Finance;

class Tradeleveraged extends Base
{
	/**
	 * 个人参数
	 * @var unknown
	 */
	private $param;
	
	public function _initialize()
	{
		parent::_initialize();
		$this->param = Param::getParam($this->user_id);
	}
	/**
	 * 获取交易对
	 * @return unknown
	 */
	public function getSymbol()
	{
		$coin_list = CoinList::where(['state' => 1])->field('id,name')->select();
		$res = [];
		foreach ($coin_list as $rows) {
			foreach ($coin_list as $row) {
				if($rows['name'] != $row['name'] && $row['name'] == 'USDT') {
					$symbole = $rows['name'].$row['name'];
					$temp = [
							'base_currency' => $rows,
							'quote_currency' => $row,
							'symbol' => strtolower($symbole)
					];
					$res[] = $temp;
				}
			}
		}
		$res = [
				'symbol' => $res,
				'fee' => $this->param['trade_fee']
		];
		return jsonSuccess($res);
	}
	
	/**
	 * 获取市场行情
	 * @return unknown
	 */
	public function getLine()
	{
		$symbol = $this->request->post('symbol');
		$marcke = new Marcketline();
		$res = $marcke->getSymbolClose($symbol);
		return jsonSuccess($res);
	}
	
	/**
	 * 杠杆买入
	 * @throws Exception
	 * @return unknown
	 */
	public function buy()
	{
		$data = $this ->request ->post('');
		Db::startTrans();
		try {
			$user = Users::get($this->user_id);
			if(!$user->is_cert)throw new Exception('请先实名认证');
			//验证数据合法性
			if(!in_array($data['trade_style'], [1,2]))
				throw new Exception('非法操作');
			//if(!$data['pay_pwd'])throw new Exception('请输入交易密码');
			if(!$data['multi'])throw new Exception('请选择杠杆倍数');
			if(!$data['capital'])throw new Exception('请选择本金');
			if(!$data['base_currency'] || !$data['quote_currency'] || !$data['symbol'])
				throw new Exception('请选择交易对');
			if($data['num'] > 20 || $data['num'] < 1)throw new Exception('手数1-20之间');
			if($data['loss_up'] > 100 || $data['loss_down'] < 10)throw new Exception('止盈止损在10%~100%');
			if($data['loss_down'] > 100 || $data['loss_down'] < 10)throw new Exception('止盈止损在10%~100%');
			if(!$data['buy_price'])throw new Exception('购买时价格');
// 			$user = Users::get($this->user_id);
// 			if(md5($data['pay_pwd']) != $user -> pay_pwd)throw new Exception('交易密码错误');
// 			unset($data['pay_pwd']);
			//添加买入记录
			$data['user_id'] = $this->user_id;
			$data['state'] = 1;
			$data['total_price'] = $data['multi'] * $data['capital'];
			$data['create_time'] = time();
			$data['update_time'] = time();
			//获取手续费
			$trade_fee = $this->param['trade_fee'];
			$start_time = strtotime($this->param['trade_start']);
			$end_time = strtotime($this->param['trade_end']);
			$now_time = time();
			if($now_time > $end_time || $now_time < $start_time)throw new Exception('不在交易时间内');
			$fee = $data['capital'] * $trade_fee / 100;
			$user_coin = CoinUser::where(['user_id' => $this->user_id,'coin_id' => $data['quote_currency']])->find();
			//判断余额
			$total_capital =  ($data['capital'] + $fee) * $data['num'];
			if($user_coin['avalible_price'] < $total_capital)
				throw new Exception('账户余额不足');
			$data['fee'] = $fee;
			//获取代理
			$act_id = Users::where(['id' => $this->user_id])->value('act_id');
			$act = Users::get($act_id);
// 			if($act->bail <= 0)throw new Exception('无法下单');
			if($act_id) {
				$param = $this->getActParam($act_id);
				$fee_act = $param['fee_rate'] * $data['fee'] / 100;
				for($i = 0 ;$i<$data['num'];$i++) {
					Users::where(['id' => $act_id])->setInc('bail',$fee_act);
					$finance = new Finance();
					$finance ->addActFinance($act_id, $this->user_id, $fee_act, "手续费收益".$fee_act, 2);
				}
				
			}
			//添加订单
			$res_data = [];
			for($i = 0;$i < $data['num'];$i ++ ){
				$res_data[] = $data;
			}
			$trade = new Leveraged();
			$trade->saveAll($res_data);
// 			Leveraged::create($data);
			//扣除用户余额
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $data['quote_currency']])->setInc('freezing_price',$total_capital);
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $data['quote_currency']])->setDec('avalible_price',$total_capital);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e -> getMessage());
		}
		$msg = $data['trade_style'] == 1 ? '买入' : '卖出';
		return jsonSuccess("{$msg}成功");
	}
	
	/**
	 * 获取代理参数
	 * @param unknown $user_id
	 * @return unknown
	 */
	public function getActParam($user_id)
	{
		$param = UserActParam::where(['user_id' => $user_id])->find();
		if(!$param) {
			$param = UserActParam::where(['id' => 1])->find();
		}
		return $param;
	}
	
	/**
	 * 获取交易列表
	 * @return unknown
	 */
	public function tradeList()
	{
		$trade_style = $this->request->post('trade_style');
		$where = ['trade_style' => $trade_style,'user_id' => $this->user_id,'state' => ['neq',2]];
		$list = Leveraged::where($where)->order('id desc')->paginate();
		return jsonSuccess($list);
	}
	
	/**
	 * 获取实时价格
	 * @return unknown
	 */
	public function getNowLine()
	{
		$marcke = new Marcketline();
		$btcusdt = $marcke->getSymbolClose('btcusdt');
		$bchusdt = $marcke->getSymbolClose('bchusdt');
		$ethusdt = $marcke->getSymbolClose('ethusdt');
		$res = [
				'btcusdt' => $btcusdt,
				'bchusdt' => $bchusdt,
				'ethusdt' => $ethusdt
		];
		return jsonSuccess($res);
	}
	
	/**
	 * 手动平仓
	 * @return unknown
	 */
	public function position()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$this->setPoisition($id);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('平仓成功');
	}
	
	/**
	 * 一键平仓
	 */
	public function allPosition()
	{
		$trade_list = Leveraged::where(['user_id' => $this->user_id,'state' => 1])->column('id');
		Db::startTrans();
		try {
			foreach ($trade_list as $val) {
				$this->setPoisition($val);
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('一键平仓成功');
	}
	
	/**
	 * 执行平仓
	 * @param unknown $id
	 * @throws Exception
	 */
	private function setPoisition($id)
	{
		$finance = new Finance();
		//获取当前订单
		$trade_order = Leveraged::get(intval($id));
		//获取用户平仓状态
		$user = Users::get($trade_order->user_id);
		if($user->is_lock)throw new Exception('当前无法平仓');
		//获取当前价格
		$marcke = new Marcketline();
		$close_line = $marcke->getSymbolClose($trade_order->symbol);
		//当前盈亏比例
		$rate = $trade_order->symbol == 'btcusdt' ?  100 / $trade_order -> multi : 10 / $trade_order -> multi ;
		$rate = ($close_line['close'] - $trade_order -> buy_price) / $rate;
		$loss_up = $trade_order->capital * $trade_order->loss_up / 100;
		$loss_down = $trade_order->capital * $trade_order->loss_down / 100;
		//如果是买入订单
		if($trade_order -> trade_style == 1) {
			$add_price = $trade_order->capital * $rate; //获取到盈亏金额
			if($rate > 0 ) {
				if($add_price > $loss_up)$add_price = $loss_up;
			}
			if($rate < 0) {
				if(-$add_price > $loss_down)$add_price = -$loss_down;
			}
		}else {
			$add_price = -$trade_order->capital * $rate; //获取到盈亏金额
			if($rate < 0) {
				if($add_price > $loss_up)$add_price = $loss_up;
			}
			if($rate > 0) {
				if($add_price > $loss_down)$add_price=$loss_down;
			}
		}
		$trade_state = Leveraged::where(['id' => $id])->value('state');
		if($trade_state != 1) throw new Exception('请刷新在平仓');
		//计算返还金额
		$res_price = $trade_order->capital + $add_price;
		$act_id = Users::where(['id' => intval($this->user_id)])->value('act_id');
		$act = Users::get($act_id);
		if($add_price < 0) {
			$add_price = -$add_price;
			Users::where(['id' => $act_id])->setInc('bail',$add_price);
			$finance ->addActFinance($act_id, $this->user_id, $add_price, "保证金收益".$add_price, 2);
		} else {
			$res_prices = $add_price;
			Users::where(['id' => $act_id])->setDec('bail',$res_prices);
			$finance ->addActFinance($act_id, $this->user_id, -$res_prices, "保证金扣除".$res_prices, 2);
		}
		//更改订单状态
		Leveraged::where(['id' => $id])->update(['state' => 0 ,'update_time' => time(),'real_price' => $add_price,'close' => $close_line['close']]);
		CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_order->quote_currency])->setInc('avalible_price',$res_price);
		CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_order->quote_currency])->setDec('freezing_price',$trade_order->capital);
	}
}